package com.java.sjzl.controller;

import com.java.sjzl.entity.Book;
import com.java.sjzl.entity.Student;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public  class ApachePoiExcelClassic<T>{

    public static void main(String[] args) {

        // 测试学生
        ApachePoiExcelClassic<Student> ex = new ApachePoiExcelClassic<>();
        String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
        List<Student> dataset = new ArrayList<>();
        dataset.add(new Student(10000001, "张三", 20, true, new Date()));
        dataset.add(new Student(20000002, "李四", 24, false, new Date()));
        dataset.add(new Student(30000003, "王五", 22, true, new Date()));

        // 测试图书
        ApachePoiExcelClassic<Book> ex2 = new ApachePoiExcelClassic<>();
        String[] headers2 = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN", "图书出版社", "封面图片" };
        List<Book> dataset2 = new ArrayList<>();

        try {
            dataset2= extracted(dataset2);
            // 导出学生信息
            OutputStream out = new FileOutputStream("E://tmp//students.xlsx");
            ex.exportExcel(headers, dataset, out);
            // 导出图书信息
            OutputStream out2 = new FileOutputStream("E://tmp//books.xlsx");
            ex2.exportExcel(headers2, dataset2, out2);

            System.out.println("学生信息Excel导出成功！，路径："+"E://tmp//students.xlsx");
            System.out.println("图书信息Excel导出成功！，路径："+"E://tmp//books.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 这是一个通用的方法，利用了JAVA的反射机制，可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
     *
     * @param title
     *            表格标题名
     * @param headers
     *            表格属性列名数组
     * @param dataset
     *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
     *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
     * @param out
     *            与输出设备关联的流对象，可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern
     *            如果有时间数据，设定输出格式。默认为"yyy-MM-dd"
     */
    public void exportExcel(String title, String[] headers,
                            Collection<T> dataset, OutputStream out, String pattern) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet(title);
        // 设置默认列宽
        sheet.setDefaultColumnWidth(20);

        // 创建样式
        CellStyle style = createStyle(workbook, IndexedColors.SKY_BLUE.getIndex(), HorizontalAlignment.CENTER, true);
        CellStyle style2 = createStyle(workbook, IndexedColors.LIGHT_YELLOW.getIndex(), HorizontalAlignment.CENTER, false);

        // 创建表头
        createHeader(sheet, style, headers);

        // 创建数据行
        int rowNum = 1;
        for (T data : dataset) {
            Row row = sheet.createRow(rowNum++);
            // For Book class
            // 将图像插入单元格中（假设preface是表示图像的字节数组）
            if (data instanceof Book) {
                sheet.setDefaultRowHeightInPoints(80);
                Book book = (Book) data;
                byte[] preface = book.getPreface(); // 假设 byte[] preface 是图像

                // 插入图书信息
                row.createCell(0).setCellValue(book.getBookId());
                row.createCell(1).setCellValue(book.getName());
                row.createCell(2).setCellValue(book.getAuthor());
                row.createCell(3).setCellValue(book.getPrice());
                row.createCell(4).setCellValue(book.getIsbn());
                row.createCell(5).setCellValue(book.getPubName());
                if (preface != null && preface.length > 0) {
                    int pictureIdx = workbook.addPicture(preface, Workbook.PICTURE_TYPE_JPEG);
                    CreationHelper helper = workbook.getCreationHelper();
                    Drawing drawing = sheet.createDrawingPatriarch();

                    // 设置图片锚点，将图片放在第6列的第rowNum-1行
                    ClientAnchor anchor = helper.createClientAnchor();
                    anchor.setCol1(6);
                    anchor.setRow1(rowNum - 1);

                    // 创建Picture对象
                    Picture pict = drawing.createPicture(anchor, pictureIdx);

                    // 设置图片大小，可以根据实际需求调整大小
                    pict.resize(1.0, 1.0);
                }
            }
            // For Student class
            else if (data instanceof Student) {
                Student student = (Student) data;
                row.createCell(0).setCellValue(student.getId());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getAge());
                row.createCell(3).setCellValue(student.isSex() ? "男" : "女"); // Assuming boolean to String
                // Format date as "yyyy-MM-dd"
                Cell dateCell = row.createCell(4);
                CellStyle dateStyle = workbook.createCellStyle();
                CreationHelper createHelper = workbook.getCreationHelper();
                dateStyle.setDataFormat(createHelper.createDataFormat().getFormat(pattern));
                dateCell.setCellValue(student.getBirthday());
                dateCell.setCellStyle(dateStyle);
            }
        }

        // 将工作簿内容写入输出流
        try {
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CellStyle createStyle(Workbook workbook, short color, HorizontalAlignment alignment, boolean bold) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(color);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(alignment);

        Font font = workbook.createFont();
        font.setColor(IndexedColors.VIOLET.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(bold);
        style.setFont(font);

        return style;
    }

    private void createHeader(Sheet sheet, CellStyle style, String[] headers) {
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(style);
        }
    }

    private static List<Book>  extracted(List<Book> dataset2) throws IOException {
        List<Book> books=new ArrayList<>();
        InputStream imageStream1 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book1.jpg");
        BufferedInputStream bis1 = new BufferedInputStream(imageStream1);
        byte[] buf1 = new byte[bis1.available()];
        while ((bis1.read(buf1)) != -1) { }
        books.add(new Book(1, "jsp", "leno", 300.33f, "1234567","清华出版社", buf1));

        InputStream imageStream2 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book2.jpg");
        BufferedInputStream bis2 = new BufferedInputStream(imageStream2);
        byte[] buf2 = new byte[bis2.available()];
        while ((bis2.read(buf2)) != -1) { }
        books.add(new Book(2, "java编程思想", "brucl", 300.33f, "1234567", "阳光出版社", buf2));

        InputStream imageStream3 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book3.jpg");
        BufferedInputStream bis3 = new BufferedInputStream(imageStream3);
        byte[] buf3 = new byte[bis3.available()];
        while ((bis3.read(buf3)) != -1) { }
        books.add(new Book(3, "DOM艺术", "lenotang", 300.33f, "1234567",  "清华出版社", buf3));

        InputStream imageStream4 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book4.jpg");
        BufferedInputStream bis4 = new BufferedInputStream(imageStream4);
        byte[] buf4 = new byte[bis4.available()];
        while ((bis4.read(buf4)) != -1) { }
        books.add(new Book(4, "java疯狂讲义", "lenotang", 300.33f, "1234567","清华出版社", buf4));

        InputStream imageStream5 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book5.jpg");
        BufferedInputStream bis5 = new BufferedInputStream(imageStream5);
        byte[] buf5 = new byte[bis5.available()];
        while ((bis5.read(buf5)) != -1) { }
        books.add(new Book(5, "java虚拟机", "leno", 400.33f, "1234567",
                "清华出版社", buf5));

        InputStream imageStream6 = ApachePoiExcelClassic.class.getClassLoader().getResourceAsStream("images/book6.jpg");
        BufferedInputStream bis6 = new BufferedInputStream(imageStream6);
        byte[] buf6 = new byte[bis6.available()];
        while ((bis6.read(buf6)) != -1) { }
        books.add(new Book(6, "java完美编程", "leno", 300.33f, "1234567",
                "汤春秀出版社", buf6));
        return books;
    }


    public void exportExcel(Collection<T> dataset, OutputStream out) {
        exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String[] headers, Collection<T> dataset,
                            OutputStream out) {
        exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
    }

    public void exportExcel(String[] headers, Collection<T> dataset,
                            OutputStream out, String pattern) {
        exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern);
    }


}




